package com.warrior.service;

import com.warrior.Exception.ProjectException;
import com.warrior.entity.ActivityEntity;
import com.warrior.entity.TeamEntity;
import com.warrior.entity.UserActivityEntity;
import com.warrior.entity.UserEntity;
import com.warrior.respository.ITeamRepository;
import com.warrior.respository.IUserActivityRepository;
import com.warrior.util.DateUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Shawn on 2017/3/15.
 */
@Service
public class TeamService {
    private static final Logger logger = LogManager.getLogger(TeamService.class.getName());

    @Autowired
    private ITeamRepository teamRepository;

    @Autowired
    private UserService userService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private IUserActivityRepository userActivityRepository;


    /**
     * 根据一个队伍对象插入一个队伍信息
     *
     * @param teamEntity
     */
    @Transactional
    public void saveNewTeam(TeamEntity teamEntity) {
        if (logger.isDebugEnabled()) {
            logger.debug("saveNewTeam(TeamEntity teamEntity={}) - start", teamEntity); //$NON-NLS-1$
        }
        this.teamRepository.saveAndFlush(teamEntity);
        //保存队伍信息同时更新用户信息
        String userId = teamEntity.getCaptionId();
        UserEntity userEntity = this.userService.findUserById(userId);
        userEntity.setIsCaption(1);
        userEntity.setTeamEntity(teamEntity);
        this.userService.saveUser(userEntity);

        if (logger.isDebugEnabled()) {
            logger.debug("saveNewTeam(TeamEntity) - end"); //$NON-NLS-1$
        }
    }

    /**
     * 根据一个队伍对象插入一个队伍信息
     *
     * @param teamEntity
     */
    @Transactional
    public void saveNewTeamWithMobile(TeamEntity teamEntity,String mobile) {
        if (logger.isDebugEnabled()) {
            logger.debug("saveNewTeam(TeamEntity teamEntity={}) - start", teamEntity); //$NON-NLS-1$
        }
        this.teamRepository.saveAndFlush(teamEntity);
        //保存队伍信息同时更新用户信息
        String userId = teamEntity.getCaptionId();
        UserEntity userEntity = this.userService.findUserById(userId);
        userEntity.setMobile(mobile);
        userEntity.setIsCaption(1);
        userEntity.setTeamEntity(teamEntity);
        this.userService.saveUser(userEntity);

        if (logger.isDebugEnabled()) {
            logger.debug("saveNewTeam(TeamEntity) - end"); //$NON-NLS-1$
        }
    }


    /**
     * 根据id找到一个队伍的信息
     *
     * @param teamId
     * @return
     */
    @Transactional(readOnly = true)
    public TeamEntity findTeamByTeamId(String teamId) {
        if (logger.isDebugEnabled()) {
            logger.debug("findTeamByTeamId(String teamId={}) - start", teamId); //$NON-NLS-1$
        }
        TeamEntity returnTeamEntity = this.teamRepository.findTeamEntityById(teamId);
        if (logger.isDebugEnabled()) {
            logger.debug("findTeamByTeamId(String) - end"); //$NON-NLS-1$
        }
        return returnTeamEntity;
    }


    /**
     * 查出所有队伍积分
     *
     * @param page 页码
     * @param size 大小
     * @return PAGE对象
     */
    @Transactional(readOnly = true)
    public Page<TeamEntity> findAllActiveTeam(int page, int size) {
        if (logger.isDebugEnabled()) {
            logger.debug("findAllActiveTeam(int page={}, int size={}) - start", page, size); //$NON-NLS-1$
        }

        Sort sort = new Sort(Sort.Direction.DESC, "teamIntegral");
        //设置分页参数
        Pageable pageable = new PageRequest(page, (size <= 0) ? 10 : size, sort);
        Page<TeamEntity> teamEntities = this.teamRepository.findTeamByTeamStatusGreaterThan(0, pageable);

        if (logger.isDebugEnabled()) {
            logger.debug("findAllActiveTeam(int, int) - end"); //$NON-NLS-1$
        }
        return teamEntities;
    }

    /**
     * 解散队伍/队员离队
     *
     * @param userId 用户id
     * @param teamId 队伍id
     * @throws ProjectException 异常
     */
    @Transactional
    public void dismissTeamByUser(String userId, String teamId) throws ProjectException {
        if (logger.isDebugEnabled()) {
            logger.debug("dismissTeamByUser(String userId={}, String teamId={}) - start", userId, teamId); //$NON-NLS-1$
        }

        //查看当前用户是否是队长
        UserEntity userEntity = this.userService.findUserById(userId);
        if (null != userEntity) {
            Integer isCaption = userEntity.getIsCaption();
            if (null != isCaption && 1 == isCaption) {
                TeamEntity teamEntity = this.findTeamByTeamId(teamId);
                //排除不能删除的队伍
                if (2 == teamEntity.getTeamStatus() || 1 == teamEntity.getIsLocked()) {
                    throw new ProjectException("职业战队不可解散");
                }
                //队长离队删除该队伍信息,并关联取消其他队员信息
                //先找到所有队员
                List<UserEntity> member = this.userService.findTeamMember(userId);
                for (UserEntity user : member) {
                    UserEntity memberUser = this.userService.findUserById(user.getId());
                    //置空外键
                    memberUser.setTeamEntity(null);
                    this.userService.saveUser(memberUser);
                }
                //去掉队长标识
                userEntity.setIsCaption(0);
                this.userService.saveUser(userEntity);
                this.teamRepository.delete(teamEntity);
            } else {
                //普通队员离队,将队伍状态变成null
                userEntity.setTeamEntity(null);
                this.userService.saveUser(userEntity);
            }

        } else {
            throw new ProjectException("未找到该用户信息");
        }

        if (logger.isDebugEnabled()) {
            logger.debug("dismissTeamByUser(String, String) - end"); //$NON-NLS-1$
        }
    }

    /**
     * 更改锁定状态
     *
     * @param teamId 队伍id
     * @param status 修改的状态
     */
    @Transactional
    public void switchLockedStatus(String teamId, int status) {
        if (logger.isDebugEnabled()) {
            logger.debug("switchLockedStatus(String teamId={}, int status={}) - start", teamId, status); //$NON-NLS-1$
        }

        TeamEntity teamEntity = this.findTeamByTeamId(teamId);
        teamEntity.setIsLocked(status);
        this.saveNewTeam(teamEntity);

        if (logger.isDebugEnabled()) {
            logger.debug("switchLockedStatus(String, int) - end"); //$NON-NLS-1$
        }
    }


    /**
     * 找出一共有多少只队伍
     *
     * @param activityId
     * @return
     */
    @Transactional
    public int getAttendTeamNum(String activityId) {
        if (logger.isDebugEnabled()) {
            logger.debug("getAttendTeamNum(String activityId={}) - start", activityId); //$NON-NLS-1$
        }

        List<UserActivityEntity> userActivityEntities = this.userService.findAllUserByActivityId(activityId);
        List<UserEntity> userEntities = new ArrayList<>();
        for (UserActivityEntity userActivityEntity : userActivityEntities) {
            //查找出所有队长,有多少队长就有多少支队伍
            UserEntity userByUserId = userActivityEntity.getUserByUserId();
            if (null != userByUserId) {
                Integer isCaption = userByUserId.getIsCaption();
                if (1 == isCaption) {
                    userEntities.add(userByUserId);
                }
            }
        }
        int returnint = userEntities.size();
        if (logger.isDebugEnabled()) {
            logger.debug("getAttendTeamNum(String) - end"); //$NON-NLS-1$
        }
        return returnint;
    }


    /**
     * 队伍参加一个新的活动
     *
     * @param teamId     队伍id
     * @param activityId 活动id
     */
    public void attendNewActive(String teamId, String activityId, String userId) throws ProjectException {
        if (logger.isDebugEnabled()) {
            logger.debug("attendNewActive(String teamId={}, String activityId={}, String userId={}) - start", teamId, activityId, userId); //$NON-NLS-1$
        }

        ActivityEntity activityEntity = this.activityService.findActivityById(activityId);
        TeamEntity teamEntity = this.findTeamByTeamId(teamId);
        if (null == activityEntity || null == teamEntity) {
            throw new ProjectException("未找到队伍或活动信息");
        }
        //判断活动参赛规则(职业队/均可参加)
        if (1 == activityEntity.getActivityType() && 2 != teamEntity.getTeamStatus()) {
            throw new ProjectException("该队伍不具备参加条件");
        }
        //判断活动是否到达截止日期
        DateUtil dateUtil = new DateUtil();
        if (activityEntity.getApplyDeadLine().before(dateUtil.Date2Timestamp(new Date()))) {
            throw new ProjectException("已经超过截止日期之前");
        }
        //判断是否达到上限
        if (activityEntity.getTeamUpperLimit() <= this.getAttendTeamNum(activityId)) {
            throw new ProjectException("该活动报名已达上限");
        }
        //判断是否是队长报名
        UserEntity userEntity = this.userService.findUserById(userId);
        if (0 == userEntity.getIsCaption()) {
            throw new ProjectException("只有队长才能报名");
        }
        //开始报名
        List<UserEntity> userEntities = this.userService.findTeamMember(userId);
        for (int i = 0; i < userEntities.size(); i++) {
            UserEntity user = userEntities.get(i);
            String userIds  = user.getId();
            this.saveUserActivityEntity(userIds,activityId);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("attendNewActive(String, String, String) - end"); //$NON-NLS-1$
        }
    }

    @Transactional
    public void saveUserActivityEntity(String userId,String activityId){
        DateUtil dateUtil = new DateUtil();
        UserActivityEntity userActivityEntity = new UserActivityEntity();
        userActivityEntity.setId("UA-"+ UUID.randomUUID().toString().replace("-",""));
        userActivityEntity.setCreatedBy("-99999");
        userActivityEntity.setUpdateBy("-99999");
        userActivityEntity.setCreatedAt(dateUtil.Date2Timestamp(new Date()));
        userActivityEntity.setUpdateAt(dateUtil.Date2Timestamp(new Date()));
        userActivityEntity.setStatus(1);
        UserEntity userEntity = this.userService.findUserById(userId);
        userActivityEntity.setUserByUserId(userEntity);
        ActivityEntity activityEntity = this.activityService.findActivityById(activityId);
        userActivityEntity.setActivityByActivityId(activityEntity);
        this.userActivityRepository.saveAndFlush(userActivityEntity);
    }


    /**
     * 根据活动找到参加的队伍信息
     *
     * @param activityId 活动id
     * @return List<TeamEntity>
     */
    @Transactional
    public List<TeamEntity> findTeamsInfoByActivityId(String activityId) {
        if (logger.isDebugEnabled()) {
            logger.debug("findTeamsInfoByActivityId(String activityId={}) - start", activityId); //$NON-NLS-1$
        }

        ActivityEntity activityEntity = this.activityService.findActivityById(activityId);
        List<UserActivityEntity> list = this.userActivityRepository.findAllUserEntityByActivityByActivityIdAndStatus(activityEntity, 2);
        List<TeamEntity> teamEntities = new ArrayList<>();
        for (UserActivityEntity userActivityEntity : list) {
            UserEntity user = userActivityEntity.getUserByUserId();
            if (1 == user.getIsCaption()) {
                TeamEntity teamEntity = user.getTeamEntity();
                teamEntities.add(teamEntity);
            }

        }

        if (logger.isDebugEnabled()) {
            logger.debug("findTeamsInfoByActivityId(String) - end"); //$NON-NLS-1$
        }
        return teamEntities;
    }


    /**
     * 查询所有队伍
     * @param size 页码数
     * @param page 当前页
     * @param orderType 排序类型
     * @return Page<TeamEntity>
     */
    @Transactional
    public Page<TeamEntity> findAllTeams(int size,int page, String orderType){
        Sort sort = new Sort(Sort.Direction.ASC, "createdAt");
        if ("desc".equals(orderType)) {
            sort = new Sort(Sort.Direction.DESC, "createdAt");
        }
        //设置分页参数
        Pageable pageable = new PageRequest(page, (size <= 0) ? 3 : size, sort);
        Page<TeamEntity> teamEntities = this.teamRepository.findAll(pageable);
        return teamEntities;
    }


    @Transactional
    public TeamEntity findTeamByTeamName(String teamName){
      return this.teamRepository.findTeamEntityByName(teamName);
    }

    @Transactional
    public TeamEntity findTeamByMobile(String mobile){
        return this.teamRepository.findTeamEntityByLeaderMobile(mobile);
    }


    @Transactional
    public List<TeamEntity> findAllTeamsByListInActivity(){
        List<TeamEntity> teamEntities = this.teamRepository.findAll();
        return teamEntities;
    }


    public void ticketSuccess(String teamId, String activityId) {
    }
}
